package com.study.hot.jetpack.paging;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.paging.PagedListAdapter;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.study.hot.R;
import com.study.hot.jetpack.room.test_address.db.Address;

import java.util.Objects;

/**
 * <pre>
 *     author : fauks
 *     time   : 2020/03/25
 *     desc   :
 * </pre>
 */
public class PagingAdapter extends PagedListAdapter<Address, PagingAdapter.PageViewHolder> {

    protected PagingAdapter() {
        super(new DiffUtil.ItemCallback<Address>() {
            @Override public boolean areItemsTheSame(@NonNull Address oldItem, @NonNull Address newItem) {
                return Objects.equals(oldItem.getAddressId(), newItem.getAddressId());
            }

            @Override public boolean areContentsTheSame(@NonNull Address oldItem, @NonNull Address newItem) {
                return oldItem.getAddressCity().equals(newItem.getAddressCity())
                        && oldItem.getAddressArea().equals(newItem.getAddressArea());
            }
        });
    }

    @NonNull @Override public PageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new PageViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_paging, parent, false));
    }

    @Override public void onBindViewHolder(@NonNull PageViewHolder holder, int position) {
        Address address = getItem(position);
        holder.tvCity.setText(address.getAddressCity());
        holder.tvArea.setText(address.getAddressArea());
    }

    static class PageViewHolder extends RecyclerView.ViewHolder {

        TextView tvCity;
        TextView tvArea;

        PageViewHolder(@NonNull View itemView) {
            super(itemView);
            tvCity = itemView.findViewById(R.id.cityTv);
            tvArea = itemView.findViewById(R.id.areaTv);
        }
    }
}
